package com.example.chess.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

public class SettingReceiver extends BroadcastReceiver implements LifecycleEventObserver {

    private static final String BROADCAST_ACTION = "com.example.chess.ACTION_SETTING_CHANGED";

    private OnSettingChangedListener onSettingChangedListener;
    private AppCompatActivity host;

    public static void sendBroadcast(Context context) {
        context.sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    private SettingReceiver(AppCompatActivity host) {
        this.host = host;
        host.registerReceiver(this, new IntentFilter(BROADCAST_ACTION));
        host.getLifecycle().addObserver(this);
    }

    public static SettingReceiver register(AppCompatActivity activity) {
        return new SettingReceiver(activity);
    }

    public void setOnSettingChangedListener(OnSettingChangedListener onSettingChangedListener) {
        this.onSettingChangedListener = onSettingChangedListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (onSettingChangedListener != null) {
            onSettingChangedListener.onSettingChanged();
        }
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            host.unregisterReceiver(this);
        }
    }

    public interface OnSettingChangedListener {
        void onSettingChanged();
    }
}
